var app = getApp();
Page({
  data: {
    petList: []
  },

  onLoad: function(options) {
    this.setData({
      statusBarHeight: app.globalData.systemInfo.statusBarHeight + 15
    })
  },
  onShow: function() {
    this.setData({
      randomNumber: Math.random(),
      petList: app.globalData.petList
    })
  },

  //更改信息
  updatePet: function(r) {
    var index = r.currentTarget.dataset.index;
    var pet = this.data.petList[index];
    wx.navigateTo({
      url: '/pages/updateePet/updateePet?pet=' + JSON.stringify(pet),
    })
  },
  //添加宠物
  addPet: function() {
    var sequence = this.data.petList.length + 1;
    wx.navigateTo({
      url: '/pages/addPet/addPet?sequence=' + sequence
    })
  },
  //返回
  rollback: function() {
    wx.navigateBack({
      delta: 1
    })
  },
  //切换顺序
  updatePetSequence: function(r) {
    var index = r.currentTarget.dataset.index;
    var pet = this.data.petList[index];
    var that = this;

    if (pet.sequence == 1) {
      this.rollback();
    } else {
      var pet1 = this.data.petList[0];
      //先把选中的顺序变成1
      wx.request({
        url: app.globalData.requestUrl + 'updatePet',
        method: 'POST',
        data: {
          id: pet.id,
          belongUserId: app.globalData.user.id,
          sequence: 1
        },
        success: function() {
          wx.request({
            url: app.globalData.requestUrl + 'updatePet',
            method: 'POST',
            data: {
              id: pet1.id,
              belongUserId: pet.belongUserId,
              sequence: pet.sequence
            },
            success: function() {
              that.getAllPetByUserId();
            }
          })
        }
      })
    }
  },
  //获取宠物列表
  getAllPetByUserId: function() {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getAllPetByUserId',
      data: {
        userId: app.globalData.user.id
      },
      success: function(r) {
        var petList = r.data.data;
        app.globalData.petList = petList;
        that.setData({
          petList: petList
        })
        that.rollback();
      }
    })
  },
})